package com.example.kotlindemo

import android.os.Bundle
import com.google.android.material.floatingactionbutton.FloatingActionButton
import androidx.appcompat.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.kotlindemo.adapter.DoubanAdapter
import com.example.kotlindemo.adapter.OnItemClickListener
import com.example.kotlindemo.http.RetrofitHelper
import com.example.kotlindemo.model.Data
import com.example.kotlindemo.model.DoubanResponse
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() , OnItemClickListener{

    private lateinit var list: RecyclerView
    private val scope = MainScope()
    private var res: DoubanResponse? = null
    private lateinit var fab: FloatingActionButton
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val toolbar: Toolbar = findViewById(R.id.toolbar)
        toolbar.title = "豆瓣电影排行"
        setSupportActionBar(toolbar)
        list = findViewById(R.id.list)
        val adapter = DoubanAdapter(this)
        list.adapter = adapter
        list.setHasFixedSize(true)
        list.layoutManager = LinearLayoutManager(this)
        fab = findViewById(R.id.fab)
        fab.setOnClickListener{
            adapter.list.removeAt(0)
            adapter.notifyItemRemoved(0)
        }
        scope.launch {
            res = RetrofitHelper.getMovieServer().getList()
            adapter.commitList(res!!.data)
        }

    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_toolbar,menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId){
            R.id.light, R.id.dark -> {
                item.isChecked = true
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        scope.cancel()
    }

    override fun onItemClick(position: Int) {
        Snackbar.make(fab,position.toString(),Snackbar.LENGTH_SHORT).show()
    }
}